<template>
    <div class="emailContainer">
        <div>当前邮箱：{{ userInfo.email === "" ? "未设置邮箱" : userInfo.email }}</div>
        <div>
            修改邮箱：
            <el-input v-model="newEmail" style="width: 20rem"></el-input>
        </div>
        <div>
            <el-button @click="submitEmail">保存</el-button>
        </div>
    </div>
</template>

<script>
import store from "@/store";
import service from "@/utils/request";
import { ElMessage } from "element-plus";

export default {
    components: {},
    data() {
        return {
            userInfo: {},
            newEmail: "",
        };
    },
    computed: {},
    methods: {
        submitEmail() {
            if (!this.newEmail.match(/^\w+@[a-z0-9]+.[a-z]{2,4}$/)) {
                ElMessage({
                    type: "error",
                    message: "邮箱格式有误",
                });
                return;
            } else {
                service({
                    method: "post",
                    url: "/user/saveUser",
                    headers: {
                        token: store.state.token,
                        "Content-type": "application/json",
                    },
                    data: {
                        ...this.userInfo,
                        email: this.newEmail,
                    },
                }).then(() => {
                    ElMessage({
                        type: "success",
                        message: "邮箱更改成功",
                    });
                    store.commit("setUserInfo");
                    // 获取用户信息
                    store.commit("getUserInfo");
                    setTimeout(() => {
                        window.location.reload();
                    }, 200);
                });
            }
        },
    },
    beforeMount() {
        this.userInfo = store.state.userInfo;
    },
};
</script>
<style lang="scss" scoped>
.emailContainer {
    display: flex;
    flex-direction: column;
    line-height: 3rem;
    padding: 0 4rem;
}
</style>
